import { defineStore } from 'pinia'

export const useThemeStore = defineStore('theme', {
  state: () => ({
    // 默认使用亮色模式
    isDark: false,
    // 系统主题偏好
    systemTheme: null as string | null
  }),

  getters: {
    // 获取当前主题名称
    themeName(): string {
      return this.isDark ? 'dark' : 'light'
    }
  },

  actions: {
    // 切换主题
    toggleTheme() {
      this.isDark = !this.isDark
      this.applyTheme()
      this.saveTheme()
    },

    // 设置主题
    setTheme(dark: boolean) {
      this.isDark = dark
      this.applyTheme()
      this.saveTheme()
    },

    // 应用主题到DOM
    applyTheme() {
      if (this.isDark) {
        document.documentElement.classList.add('dark-theme')
        document.documentElement.classList.remove('light-theme')
      } else {
        document.documentElement.classList.add('light-theme')
        document.documentElement.classList.remove('dark-theme')
      }
    },

    // 保存主题到localStorage
    saveTheme() {
      localStorage.setItem('open-nav-theme', this.isDark ? 'dark' : 'light')
    },

    // 从localStorage加载主题
    loadTheme() {
      const savedTheme = localStorage.getItem('open-nav-theme')
      if (savedTheme) {
        this.isDark = savedTheme === 'dark'
      } else {
        // 检测系统主题偏好
        this.detectSystemTheme()
      }
      this.applyTheme()
    },

    // 检测系统主题偏好
    detectSystemTheme() {
      if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        this.systemTheme = 'dark'
        this.isDark = true
      } else {
        this.systemTheme = 'light'
        this.isDark = false
      }

      // 监听系统主题变化
      if (window.matchMedia) {
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
          this.systemTheme = e.matches ? 'dark' : 'light'
          // 只有在没有手动设置过主题的情况下才跟随系统
          if (!localStorage.getItem('open-nav-theme')) {
            this.isDark = e.matches
            this.applyTheme()
          }
        })
      }
    }
  }
})
